package youleche.com.controler.servlet;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import youleche.com.business.BVehicleImageInfo;
import youleche.com.common.IDFactory;
import youleche.com.model.MVehicleImageInfo;
import youleche.com.sql.servlet.common.SuperHttpServlet;
import youleche.com.util.DateUtil;

/**
 * 图片上传
 */
public class SHomeImgUploadServlet extends SuperHttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SHomeImgUploadServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("rawtypes")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (!item.isFormField()) {
					if (item.getName() != null && !item.getName().equals("")) {
						String fileName = item.getName();
						String extName = "";
						if(fileName.lastIndexOf(".") >= 0){
							extName = fileName.substring(fileName.lastIndexOf("."));
							String newFileName = IDFactory.getId("youleche", "vehicleImageInfo") + extName;
							String filePath = this.getServletConfig().getServletContext().getRealPath("") + "/vehicleImage/" + newFileName;
							Image bufImg = ImageIO.read(item.getInputStream());
							int width = 600;
							int height = 300;
				            BufferedImage bf = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
				            bf.getGraphics().drawImage(bufImg,0,0,width,height,null);
				            FileOutputStream newimage=new FileOutputStream(filePath);
				            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
				            encoder.encode(bf);
				            newimage.close();
							this.addVehicleImageInfo("/vehicleImage/" + newFileName, response);
					        break;
						}else{
							continue;
						}
					}else{
						continue;
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
			super.response(response, "false");
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "false");
		}
	}
	
	/**
	 * 添加图片信息
	 * @param filePath 文件路径
	 */
	private void addVehicleImageInfo(String filePath, HttpServletResponse response){
		this.asynAdd(filePath);
		super.response(response, filePath);
	}
	
	private void asynAdd(String filePath){
		MVehicleImageInfo image = new MVehicleImageInfo();
		image.setAddTime(DateUtil.getNowDate());
		image.setImageId(IDFactory.getId("youleche", "vehicleImageInfo"));
		image.setImagePath(filePath);
		image.setImageType("99");
		image.setSellerId("youleche");
		image.setVehicleId("12312321312321321323");
		try {			
			BVehicleImageInfo handler = new BVehicleImageInfo();
			handler.addVehicleImageInfo(image);
		} catch (Exception e) {
		}
	}
}
